package com.chukun.concurrency.syncCollecton;

import com.chukun.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 使用 Collections.synchronizedxxx方法
 * 类似的还有，list，set相关的方法，但是这些方法都是通过在方法上加synchronized实现的,
 * 高并发的情况下，不推荐使用
 */
@Slf4j
@ThreadSafe
public class CollectionsSyncOperator {

    //并发线程总数
    private static final int totalThreadCount=1000;

    //允许同时访问的总数
    private static final int allowThreadCount = 200;

    private static Map<Integer, Integer> map = Collections.synchronizedMap(new Hashtable<>());

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalThreadCount);
        Semaphore semaphore = new Semaphore(allowThreadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalThreadCount;i++){
            final int count = i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("error count add ",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("size: "+ map.size());
    }

    private static void add(int i){
        map.put(i,i);
    }
}
